<template>
  <el-dialog
    :title="isEdit ? '编辑当前公司' : '新增下级公司'"
    v-model="dialogVisible"
    width="520px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    class="department-dialog"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
      class="dialog-form"
    >
      <div class="form-content">
        <div class="form-wrapper">
          <el-form-item label="上级公司" v-if="!isEdit">
            <el-input
              v-model="parentName"
              disabled
              class="parent-input"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="公司名称" prop="shop_name">
            <el-input
              v-model="formData.shop_name"
              placeholder="2-10个字符"
              maxlength="10"
              show-word-limit
              clearable
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="组织编码" prop="selfid_str">
            <el-input
              v-model="formData.selfid_str"
              placeholder="2-10个字符，唯一"
              maxlength="10"
              show-word-limit
              clearable
              style="width: 300px"
            />
          </el-form-item>
          <!-- <el-form-item label="负责人" prop="manager">
            <el-input
              v-model="formData.manager"
              placeholder="2-60个字符，唯一"
             
             
              clearable
              style="width: 300px"
            />
          </el-form-item> -->

          <el-form-item label="负责人">
            <el-cascader
              v-model="formData.manager"
              :options="departmentOptions"
              :props="cascaderProps"
              separator="-"
              placeholder="请选择分管领导"
              clearable
              style="width: 300px"
              @change="handleLeaderChange"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-button">
          取 消
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isEdit ? "确 认" : "新 增" }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import type { DepartmentItem } from "@/api/types/department";
import type {
  DepartmentDialogProps,
  DepartmentDialogEmits,
} from "@/types/components";
import { getDepartmentList } from "@/api/department";
import { getUserInfo } from "@/api/employee";

const props = defineProps<DepartmentDialogProps>();
const emit = defineEmits<DepartmentDialogEmits>();

const formRef = ref<FormInstance>();
const dialogVisible = ref(props.visible);
const loading = ref(false);

//部门原始数据
const bumendata = ref(<Array<unknown> | any>[]);

// 表单数据
const formData = reactive<{
  shop_name: string;
  selfid_str: string;
  selfid?: number;
  manager?: string;
  memberCount?: number;
  leader?: number;
  isarea?: number;
}>({
  shop_name: "",
  selfid_str: "",
  selfid: undefined,
  manager: undefined,
  memberCount: undefined,
  leader: undefined,
  isarea: 1,
});

// 表单校验规则
const rules = {
  shop_name: [
    { required: true, message: "请输入组织名称", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  selfid_str: [
    { required: true, message: "请输入组织编码", trigger: "blur" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符", trigger: "blur" },
  ],
  manager: [
    { required: true, message: "请输入负责人名称", trigger: "blur" },
    { min: 2, max: 60, message: "长度在 2 到 60 个字符", trigger: "blur" },
  ],
};

// 计算上级组织名称
const parentName = computed(() => props.parentDept?.shop_name || "");

// 监听visible变化
watch(
  () => props.visible,
  (val) => {
    dialogVisible.value = val;
    if (val) {
      if (props.isEdit && props.editData) {
        // 编辑模式，填充表单数据
        fillEditData();
      } else {
        // 新增模式，确保表单为空
        resetForm();
      }
    }
  }
);

// 重置表单数据（用于新增模式）
const resetForm = () => {
  // 重置所有字段为初始状态
  Object.assign(formData, {
    shop_name: "",
    selfid_str: "",
    isarea: 1,
    selfid: undefined,
    manager: undefined,
    memberCount: undefined,
    leader: undefined,
  });

  // 重置表单验证状态
  nextTick(() => {
    formRef.value?.clearValidate();
  });
};

// 填充编辑数据
const fillEditData = () => {
  if (props.editData) {
    Object.assign(formData, {
      shop_name: props.editData.shop_name,
      selfid_str: props.editData.selfid.toString(),
      selfid: props.editData.selfid,
      manager: props.editData.manager,
      memberCount: props.editData.memberCount,
      leader: props.editData.leader
        ? [undefined, props.editData.leader]
        : undefined,
      isarea: props.editData.isarea,
    });

    // 手动触发表单验证
    nextTick(() => {
      formRef.value?.validate();
    });
  }
};

// 关闭弹窗
const handleClose = () => {
  resetForm(); // 关闭时重置表单
  emit("update:visible", false);
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  const aa=formData.manager[1]
formData.manager=aa

  try {
    await formRef.value.validate();
    if (props.isEdit) {
      // 编辑模式提交
      emit("submit", {
        shop_name: formData.shop_name,
        selfid: parseInt(formData.selfid_str),
        isarea: props.editData?.pid === 0 ? 1 : 0, // 修改这里：pid === 0 时为一级门店
        manager: formData.manager,
      });
    } else {
      // 新增模式提交
      emit("submit", {
        shop_name: formData.shop_name,
        selfid: parseInt(formData.selfid_str),
        pid: props.parentDept?.selfid,
        isarea: props.parentDept?.pid === 0 ? 0 : 1, // 修改这里：父级 pid === 0 时为二级门店
        manager: formData.manager,
      });
    }
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 部门选项
const departmentOptions = ref([]);
// 当前选中的员工信息
const selectedLeader = ref({
  name: "",
  id: null,
});

// 级联选择器配置
const cascaderProps = {
  lazy: true,
  multiple: false,
  expandTrigger: "hover",
  value: "value",
  label: "label",
  lazyLoad: async (node: any, resolve: any) => {
    console.log(node);
    
    const { level } = node;

    const demoid = ref("");

    console.log(node.label);
    if (node.label != undefined) {
      bumendata.value.forEach((item) => {
        if (node.label == item.dept_name) {
          demoid.value = item.selfid;
        }
      });
    }

    if (level === 0) {
      // 加载部门列表
      try {
        const res = await getDepartmentList();
        console.log("部门列表响应:", res);

        bumendata.value = res.data.info_list;

        if (res.code === "200" && res.data?.info_list) {
          const departments = res.data.info_list.map((dept: any) => ({
            value: dept.dept_name,
            label: dept.dept_name,
            leaf: false,
          }));
          console.log("处理后的部门数据:", departments);
          resolve(departments);
        } else {
          console.error("部门数据格式错误:", res);
          resolve([]);
        }
      } catch (error) {
        console.error("获取部门列表失败:", error);
        resolve([]);
      }
    } else if (level === 1) {
      // 加载员工列表
      try {
        const deptId = demoid.value;
        console.log(deptId);

        console.log("正在获取部门ID为", deptId, "的员工列表");
        const res = await getUserInfo(deptId);
        console.log("员工列表响应:", res);

        if (res.code === "200" && Array.isArray(res.data)) {
          const employees = res.data.map((emp: any) => ({
            value: emp.username,
            label: emp.username,
            leaf: true,
          }));
          console.log("处理后的员工数据:", employees);
          resolve(employees);
        } else {
          console.error("员工数据格式错误:", res);
          resolve([]);
        }
      } catch (error) {
        console.error("获取员工列表失败:", error);
        resolve([]);
      }
    }
  },
};

// 处理选择变化
const handleLeaderChange = (value: any[]) => {


  if (value && value.length === 2) {
    // 第一个值是部门ID，第二个值是员工ID
    formData.leader = value[1]; // 只保存员工ID
  } else {
    formData.leader = undefined;
  }
};
</script>

<style lang="scss" scoped>
.department-dialog {
  :deep(.el-dialog__header) {
    margin-right: 0;
    padding: 20px 24px;
    border-bottom: 1px solid #dcdfe6;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }

  :deep(.el-dialog__body) {
    padding: 24px;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid #dcdfe6;
  }

  .dialog-form {
    .form-content {
      display: flex;
      flex-direction: column;
      width: 100%;
      padding: 0 20px;
    }

    .form-wrapper {
      width: 100%;
      max-width: 420px;
      margin: 0 auto;
    }

    :deep(.el-form-item) {
      margin-bottom: 22px;
      width: 100%;
      display: flex;
      justify-content: flex-start;
    }

    :deep(.el-form-item__content) {
      flex: none;
      margin-left: 0 !important;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #606266;
      width: 100px !important;
      justify-content: flex-end;
      padding-right: 12px;
    }

    .parent-input {
      :deep(.el-input__wrapper) {
        background-color: #f5f7fa;
      }
    }

    :deep(.el-input__wrapper),
    :deep(.el-textarea__inner) {
      box-shadow: 0 0 0 1px #dcdfe6 inset;

      &:hover {
        box-shadow: 0 0 0 1px #c0c4cc inset;
      }

      &.is-focus {
        box-shadow: 0 0 0 1px #409eff inset;
      }
    }

    :deep(.el-input-group__append) {
      background-color: #f5f7fa;
      color: #909399;
      padding: 0 12px;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: center;
    gap: 12px;

    .cancel-button {
      margin-right: 0;
    }

    .el-button {
      padding: 8px 24px;
      min-width: 96px;
    }
  }
}

:deep(.el-select-dropdown__item) {
  padding: 8px 16px;
}
</style>
